﻿using System;
using Newtonsoft.Json;
using WholesaleOnline.Contract;
using WholesaleOnline.Controller.Extension;
using WholesaleOnline.Controller.Request;
using WholesaleOnline.Controller.Routing;
using WholesaleOnline.Controller.Storage;
using WholesaleOnline.DataContract.Messaging;
using WholesaleOnline.Model;

namespace WholesaleOnline.Controller.Handlers
{
    public class GetProductsAndCategoriesHandler : RequestHandler
    {
        private IInventoryService m_inventoryService = null;

        public GetProductsAndCategoriesHandler(IHttpStorage storage, IInventoryService inventoryService)
            : base(Routes.GET_PRODUCTS_AND_CATEGORIES, storage)
        {
            m_inventoryService = inventoryService;
        }

        public override void Handle(WebRequest webRequest)
        {
            if (Route.Matches(webRequest))
            {
                GetInventoryProductsAndCategoriesRequest request = new GetInventoryProductsAndCategoriesRequest
                {
                    BuyerId = SessionCache.LognID,
                    SellerId = webRequest.QueryArguments.ExtractFor<Guid>("seller"),
                    Keyword = webRequest.QueryArguments.ExtractFor<string>("keyword"),
                    Type = webRequest.QueryArguments.ExtractFor<InventoryType>("type")
                };

                GetInventoryProductsAndCategoriesResponse response = m_inventoryService.GetProductsAndCategoriesBy(request);
                if (response.Success)
                {
                    var result = new
                    {
                        products = response.Products.ConvertToJsonModel(),
                        categories = response.Categories.ConvertToCategoryJsonModel(response.DisplayCategoryIds)
                    };
                    Storage.Add(HttpStorageKeys.Json, JsonConvert.SerializeObject(result));
                }
                else
                {
                    Storage.Add(HttpStorageKeys.Json, "{\"products\":[],\"categories\":[]}");
                    Storage.Add(HttpStorageKeys.Exception, response.Message);
                }
            }
            else
            {
                base.NextHandler.Handle(webRequest);
            }
        }
    }
}
